﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using ObjectBakery.Adapters.Strategies;
using System.Collections;

namespace ObjectBakery.Adapters
{

    public class AdapterFactory<Tin, Tout>
    {
        Type tin = typeof(Tin);
        Type tout = typeof(Tout);

        public AdapterFactory(){}

        public IAdapterStrategy<Tin, Tout> GetAdapter<T>(Tin reference)
        {
            var type = typeof(T);
            return (Adapter<Tin, Tout>)GetAdapter(reference, type);
        }
        public IAdapterStrategy<Tin, Tout> GetAdapter(Tin reference, Type type)
        {
            Type typeIn = reference.GetType();

            object strategy = null;
          

            // permutations

            //7 DataTable -> DataTable
           
            //9 DataTable -> IList
            if (typeIn.Equals(typeof(DataTable)) && tout.Equals(typeof(IList)))
            {
                object cast = (object)reference;
                DataTable dt = cast as DataTable;
               
                strategy = new Adapter<DataTable, IList>(new DataTableToListAdapter(dt, type)); 
            }
           
            //6 IList -> DataTable
            else if (reference is IList && tout.Equals(typeof(DataTable)))
            {
                object cast = (object)reference;
                IList list = cast as IList;
                strategy = new Adapter<IList, DataTable>(new ListToDataTableAdapter(list, type));
            }

            //4 IList -> IList

            
            if (strategy == null)
                throw new ArgumentException("No matching strategy for types specified.  Feel free to implement your own.");

            return (IAdapterStrategy<Tin, Tout>)strategy;
        }
    }
}
